package com.destinomusical.epura.ws;

import java.util.ArrayList;
import java.util.List;

import android.app.ProgressDialog;
import android.content.Context;
import android.os.AsyncTask;
import android.util.Log;

import com.destinomusical.epura.interfaces.WSInterface;
import com.destinomusical.epura.obj.SearchParams;
import com.smartthinking.destinomusical.R;

public class WSCallTask extends AsyncTask<SearchParams, Void, List<?>> {

	WSInterface listener = null;
	ProgressDialog dialog = null;
	Context context;
	boolean cancelTask = false;
	boolean show = true;

	ConexionHTTP busqueda;

	public WSCallTask(WSInterface listener, Context context) {
		this.listener = listener;
		this.context = context;
		dialog = new ProgressDialog(context);
	}

	public WSCallTask(WSInterface listener, Context context, boolean show) {
		this.listener = listener;
		this.context = context;
		this.show = show;
		dialog = new ProgressDialog(context);
	}

	@Override
	public void onPreExecute() {
		if (show) {
			this.dialog.setMessage(context.getString(R.string.msg_wait));
			this.dialog.setCancelable(true);
			this.dialog.show();
		}
	}

	@Override
	protected List<?> doInBackground(SearchParams... args) {
		List<?> list = new ArrayList();
		try {
			busqueda = new ConexionHTTP();
			list = busqueda.consulta(args[0]);

		} catch (Exception e) {
			list = null;
			Log.e("WSCallTask", "Error en al extraer la lista de resultados");
		}

		return list;
	}

	@Override
	protected void onPostExecute(final List<?> list) {
		if (show)
			closeDialog();
		listener.onWSInterfaceComplete(list);
	}

	@Override
	protected void onCancelled() {
		closeDialog();
		cancelTask = true;
		listener.onWSInterfaceCancel(true);

	}

	public void closeDialog() {
		if (dialog != null && dialog.isShowing()) {
			dialog.dismiss();
			dialog = null;
		}
	}

}